import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login'
import  {checktoken}  from  '../apis/users'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/index',
    name: 'Index',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import( /* webpackChunkName: "about" */ '../views/Index'),
    // 嵌套二级路由
    children: [{
        path: '/index/accountlist',//账号管理/账号列表
        name: 'accountlist',
        component: () => import('../views/account/AccountList')
      },
      {
        path: '/index/addaccount',//账号管理/添加账号
        name: 'addaccount',
        component: () => import('../views/account/Addaccount')
      },
      {
        path: '/index/changepwd',//账号管理/修改密码
        name: 'changepwd',
        component: () => import('../views/account/Changepwd')
      },
      {
        path: '/index/home',//后台首页
        name: 'home',
        component: () => import('../views/home.vue')
      }, {
        path: '/index/administration',//店铺管理
        name: 'administration',
        component: () => import('../views/Administration.vue')
      },{
        path: '/index/order',      // 订单管理
        name: 'order',
        component: () => import('../views/Order.vue')
      },{
        path: '/index/commoditylist',//商品管理/商品列表
        name: 'commoditylist',
        component: () => import('../views/commodity/Commoditylist.vue')
      },{
        path: '/index/addommodity',//商品管理/添加商品
        name: 'addcommodity',
        component: () => import('../views/commodity/Addommodity.vue')
      },{
        path: '/index/commoditytype',//商品管理/商品类型
        name: 'commoditytype',
        component: () => import('../views/commodity/Commoditytype.vue')
      },
      {
        path: '/index/cmdtatistics',              // 销售统计/商品统计
        name: 'cmdtatistics',
        component: () => import('../views/statistics/Cmdtatistics.vue')
      },
      {
        path: '/index/orderstatistics',      // 销售统计/订单统计
        name: 'orderstatistics',
        component: () => import('../views/statistics/Orderstatistics.vue')
      },
      {
        path: '/index/userinfo',      // 销售统计/订单统计
        name: 'userinfo',
        component: () => import('../views/UserInfo.vue')
      },
    ],
  },
  {
    path: '*',//当网址输入错误是展示的页面
    name: '404',
    component: () => import('../views/Error404')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  // console.log(from)
  if(to.path=="/"){
    next()
  }else{
    checktoken({token:localStorage.token}).then(res=>{
      if(res.data.code==0){//token有效，还在有效期
        next()
      }else{
        //token失效，不能强行闯入系统！！！需要拦截，必须要登录
        next('/') //传入/，让next前往/（登录页面）
      }
    })
  }
})
export default router